<?php

class CALCULATOR
{
    function __construct(){
        require('db.php');
    }
    
    function calc($ans)	{
        $post = str_replace('×','*', $ans);
        $post = ereg_replace ('(^0-9\+-\*\/\(\) )', '', $post);
        $post = create_function("", "return({$post});" );
        $this->log($ans);
        return $post();
    }

    function log($log){
        $log = mysql_escape_string($log);
        mysql_query("INSERT INTO  `calc`.`log` (`userid` ,`date` ,`value`)
                        VALUES ('{$_SESSION['id']}', CURRENT_TIMESTAMP ,  '{$log}');") or die(mysql_error());
    }
    
    function history(){
        $user_history = "SELECT * FROM log WHERE `userid`='{$_SESSION['id']}' ORDER BY date DESC LIMIT 0,20;";
        $history = mysql_query($user_history) or die(mysql_error()); 
        $ulog = '';
        while ($row=mysql_fetch_array($history)){
            $ulog .= "<tr>
                <td class='history_date'>{$row['date']}</td>
                <td class='history_val'>{$row['value']}</td>
                <td class='history_rep' onclick='repeat({$row['id']})'>repeat</td></tr>";
        }
        return "<h2>History</h2><table class='history'>{$ulog}</table>";
    }

    function clearme($val){
        $for_clear = Array('cos(','log(','sin(','sqrt(',')');
        foreach($for_clear as $oops){
            $val = str_replace($oops,'',$val);
        }
        return $val;
    }
    
    function repeat($id){
        $id = (int) $id;
        $user_history = "SELECT * FROM log WHERE `userid`='{$_SESSION['id']}' AND `id`='{$id}' LIMIT 0,1;";
        $history = mysql_query($user_history) or die(mysql_error()); 
        while ($row=mysql_fetch_array($history)){
            $clear = $this->clearme($row['value']);
            //return $clear." - ".$row['value'];
            if(strpos($row['value'],"os")){
                return $this->cos($clear);
            } else if(strpos($row['value'],"in")){
                return $this->sin($clear);
            } else if (strpos($row['value'],"og")){
                return $this->log($clear);
            } else if (strpos($row['value'],"qrt")){
                return $this->sqrt($clear);
            } else {
                return $this->calc($row['value']);
            }
        }
    }
    
    
    function cos($v){
        $v = (int) $v;
        $this->log("cos({$v})");
        return cos(deg2rad($v));
    }
    function sin($v){
        $this->log("sin({$v})");
        $v = (int) $v;
        return sin(deg2rad($v));
    }
    function log10($v){
        $this->log("log({$v})");
        $v = (int) $v;
        return log10($v);
    }
    function sqrt($v){
        $this->log("sqrt({$v})");
        $v = (int) $v;
        return sqrt($v);
    }
    
}

?>
